<?php

namespace app\beautiful\controller\admin\setting;

use app\BaseController;

use app\beautiful\model\partner\BonusModel;
use app\beautiful\model\partner\PartnerBonusModel;
use app\beautiful\model\setting\PartnerBonusSettingModel;
use app\beautiful\model\setting\PartnerDividendSettingModel;
use app\beautiful\model\setting\PartnerPromotionSettingModel;
use app\beautiful\model\setting\PartnerTaskBonusSettingModel;
use app\common\model\ShopDetailModel;
use think\facade\Db;


class Partner extends BaseController{
    public function showOpen(){
        $type = $this->request->param('type/d',1);//1分成2分红
        $shop_detail = ShopDetailModel::where('shop_id',$this->request->shopId)->find();
        $retutn['is_open'] = $type==1?$shop_detail->is_open_partner_dividend:$shop_detail->is_open_partner_manage;
        return $this->success($retutn);
    }
    public function openSet(){
        $type = $this->request->param('type/d',1);//1分成2分红
        $is_open = $this->request->param('is_open/d',0);
        if($type==1){
            $data['is_open_partner_dividend'] = $is_open;
        }else{
            //判断是否设置数据，没有设置完则不能开启
            if($is_open==1){
                $bonus_setting = PartnerBonusSettingModel::where('shop_id',$this->request->shopId)->where(['is_delete'=>0])->find();
                if(empty($bonus_setting)) return $this->error('没有设置分红数据，不能开启');
                if($bonus_setting->mon_av_turnover==0 || $bonus_setting->per_share_price==0 || empty($bonus_setting->bonus_share_get_type) || empty($bonus_setting->join_bonus_role_id)){
                    return $this->error('分红数据设置不完整，不能开启');
                }
            }

            $data['is_open_partner_manage'] = $is_open;
        }

        ShopDetailModel::where('shop_id',$this->request->shopId)->save($data);

        return $this->success('设置成功');
    }
    /*获取所有合伙人分成设置和推广分成设置*/
    public function getDividendSet(){
        //推广分成方式
        if(null === $promotion_setting = PartnerPromotionSettingModel::where('shop_id',$this->request->shopId)->where(['is_delete'=>0])->find()){

            $promotion_setting = new PartnerPromotionSettingModel();
            $promotion_setting->shop_id = $this->request->shopId;
            $promotion_setting->dividend_type = 2;
            $promotion_setting->save();
        }
        $return['promotion_setting'] = $promotion_setting;

        //默认数据
        $dividend_setting['range'] = [];
        $dividend_setting['is_bind_shareholder'] = 1;
        $dividend_setting['store_value_type'] = 1;
        $dividend_setting['store_value_time'] = 0;
        $dividend_setting['staff_type'] = 1;
        $dividend_setting['achievement_type'] = 1;
        $dividend_setting['achievement_cycle_type'] = 1;
        $dividend_setting['is_up'] = 0;
        $dividend_setting['shop_id'] = $this->request->shopId;

        $str[]=[
            'name'=>'tz_dividend_setting',
            'role_id'=>5
        ];
        $str[]=[
            'name'=>'cz_dividend_setting',
            'role_id'=>6
        ];
        $str[]=[
            'name'=>'yg_dividend_setting',
            'role_id'=>2
        ];

        $dividend_setting_model = new PartnerDividendSettingModel();

        for($i=0;$i<count($str);$i++){
            $name = $str[$i]['name'];
            $role_id = $str[$i]['role_id'];
            $setting = $dividend_setting_model->getById(['shop_id'=>$this->request->shopId,'is_delete'=>0,'role_id'=>$role_id],'*','range');
            if(null===$setting){
                $dividend_setting_data['valid_type'] = 1;
                $dividend_setting_data['shop_id'] = $this->request->shopId;
                $dividend_setting['role_id'] = $dividend_setting_data['role_id'] = $role_id;
                PartnerDividendSettingModel::insert($dividend_setting_data);

                $setting = $dividend_setting;
            }
            $setting['range'] = $this->dividendSetRange($setting['is_up'],$setting['range']);
            $return[$name] = $setting;
        }

        //合伙人管理系统开关
        $shop_detail = ShopDetailModel::where('shop_id',$this->request->shopId)->find();
        $return['is_open_partner_manage'] = $shop_detail->is_open_partner_manage;
        return $this->success($return);

    }
    protected function dividendSetRange($is_up,$range){

        if($is_up && $range){
            for($i=0;$i<count($range);$i++){
                if($range[$i]['end']>=99999999){
                    $range[$i]['end'] = '以上';
                }
            }
        }
        return $range;
    }

    /*推广分成设置*/
    public function savePromotionSet(){
        //分红类型： 1按实付金额  2 按商品毛利
        $dividend_type = $this->request->param('dividend_type/d',2);

        if(null === $promotion_setting = PartnerPromotionSettingModel::where('shop_id',$this->request->shopId)->where(['is_delete'=>0])->find()){

            $promotion_setting=new PartnerPromotionSettingModel();
            $promotion_setting->shop_id = $this->request->shopId;
        }

        $promotion_setting->dividend_type = $dividend_type;
        $promotion_setting->save();

        return $this->success('操作成功');
    }

    public function showDividendSetOld()

    {
        $role_id = $this->request->param('role_id/d',0);

        //判断传来的参数
        if(!in_array($role_id,[2,5,6])) return $this->error('参数错误');

        if(null === $dividend_setting = PartnerDividendSettingModel::where('shop_id',$this->request->shopId)->where(['is_delete'=>0,'role_id'=>$role_id])->json(['range'],true)->find()){

            $dividend_setting = new PartnerDividendSettingModel();
            $dividend_setting->shop_id = $this->request->shopId;
            $dividend_setting->role_id = $role_id;
            $dividend_setting->save();
            $dividend_setting->range = [];
            $dividend_setting->is_bind_shareholder = 1;
            $dividend_setting->store_value_type = 1;
            $dividend_setting->store_value_time = 0;
            $dividend_setting->staff_type = 1;
            $dividend_setting->achievement_type = 1;
            $dividend_setting->achievement_cycle_type = 1;
            $dividend_setting->is_up = 0;

        }
        $range = $dividend_setting->range;
        if($dividend_setting->is_up==1 && $range){
            for($i=0;$i<count($range);$i++){

                if($range[$i]['end']>=99999999){
                    $range[$i]['end'] = '以上';
                }
            }
        }
        $dividend_setting->range = $range;
        $return['detail'] = $dividend_setting;
        return $this->success($return);

    }
    /*合伙人分成设置*/
    public function saveDividendSet()

    {
        $role_id = $this->request->param('role_id/d',0);
        $range = $this->request->param('range/a',[]);
        $is_bind_shareholder = $this->request->param('is_bind_shareholder/d',0);
        $store_value_type = $this->request->param('store_value_type/d',1);
        $store_value_time = $this->request->param('store_value_time/d',0);
        $staff_type = $this->request->param('staff_type/d',3);
        $achievement_type = $this->request->param('achievement_type/d',1);
        $achievement_cycle_type = $this->request->param('achievement_cycle_type/d',1);
        $is_up = $this->request->param('is_up/d',0);
        $valid_type = $this->request->param('valid_type/d',1);

        //测试数据
//        $range[]=[
//            'start'=>1,
//            'end'=>100,
//            'ratio'=>50
//        ];
//        $range[]=[
//            'start'=>101,
//            'end'=>99999999,
//            'ratio'=>50
//        ];
        if(null === $dividend_setting = PartnerDividendSettingModel::where('shop_id',$this->request->shopId)->where(['is_delete'=>0,'role_id'=>$role_id])->find()){

            $dividend_setting=new PartnerDividendSettingModel();
            $dividend_setting->shop_id = $this->request->shopId;
        }
        //判断传来的参数
        if(!in_array($role_id,[2,5,6])) return $this->error('参数错误');
        $dividend_setting->role_id = $role_id;
        $dividend_setting->range = json_encode($range,true);
        $dividend_setting->is_bind_shareholder = $is_bind_shareholder;

        if(in_array($store_value_type,[2,6])) $dividend_setting->store_value_type = $store_value_type;
        if(in_array($store_value_type,[2,6])) $dividend_setting->store_value_time = $store_value_time;

        $dividend_setting->staff_type = $staff_type;
        $dividend_setting->is_up = $is_up;

        if($store_value_type==2) $dividend_setting->achievement_type = $achievement_type;
        if($store_value_type==2) $dividend_setting->achievement_cycle_type = $achievement_cycle_type;
        $dividend_setting->valid_type = $valid_type;

        $dividend_setting->save();
        
        return $this->success('操作成功');

    }

    public function showBonus(){
        if(null === $bonus_setting = PartnerBonusSettingModel::where('shop_id',$this->request->shopId)->where(['is_delete'=>0])->find()){

            $bonus_setting = new PartnerBonusSettingModel();
            $bonus_setting->shop_id = $this->request->shopId;
            $bonus_setting->mon_av_turnover = 0;
            $bonus_setting->total_bonus_share = 0;
            $bonus_setting->per_share_price = 0;
            $bonus_setting->total_share_num = 0;
            $bonus_setting->bonus_share_get_type = null;
            $bonus_setting->join_bonus_role_id = null;
            $bonus_setting->bonus_budget = 0;
            $bonus_setting->buy_bonus_budget = 0;
            $bonus_setting->normal_bonus_budget = 0;
            $bonus_setting->bonus_budget_type = 1;
            $bonus_setting->bonus_cycle_type = 1;
            $bonus_setting->bonus_num = 6;
            $bonus_setting->save();

        }
        if(null === $task_bonus_setting = PartnerTaskBonusSettingModel::where('shop_id',$this->request->shopId)->where(['is_delete'=>0])->find()){

            $task_bonus_setting = new PartnerTaskBonusSettingModel();
            $task_bonus_setting->shop_id = $this->request->shopId;
            $task_bonus_setting->status = 0;
            $task_bonus_setting->consume_task_type = 0;
            $task_bonus_setting->consume_price = 0;
            $task_bonus_setting->consume_type = 1;
            $task_bonus_setting->consume_bonus_ratio = 0;
            $task_bonus_setting->toker_task_type = 0;
            $task_bonus_setting->toker_consume_price = 0;
            $task_bonus_setting->toker_consume_type = 1;
            $task_bonus_setting->toker_bonus_ratio = 0;
            $task_bonus_setting->promotion_task_type = 0;
            $task_bonus_setting->promotion_share_num = 0;
            $task_bonus_setting->promotion_bonus_ratio = 0;
            $task_bonus_setting->is_memeber_once = 0;
            $task_bonus_setting->same_member_time = 0;
            $task_bonus_setting->join_role_id = null;
            $task_bonus_setting->save();

        }
        $bonus_setting->bonus_share_get_type = $bonus_setting->bonus_share_get_type?explode(',',$bonus_setting->bonus_share_get_type):null;
        $bonus_setting->join_bonus_role_id = $bonus_setting->join_bonus_role_id?explode(',',$bonus_setting->join_bonus_role_id):null;
        $task_bonus_setting->join_role_id = $task_bonus_setting->join_role_id?explode(',',$task_bonus_setting->join_role_id):null;
        $return['bonus_detail'] = $bonus_setting;
        $return['task_bonus_detail'] = $task_bonus_setting;
        return $this->success($return);



    }
    /*分红(任务分红)设置*/
    public function saveBonus(){
        //分红设置
        $mon_av_turnover = $this->request->param('mon_av_turnover/f',0);
        $per_share_price = $this->request->param('per_share_price/f',0);
        $total_share_num = $this->request->param('total_share_num/d',0);
        $bonus_share_get_type = $this->request->param('bonus_share_get_type');
        $join_bonus_role_id = $this->request->param('join_bonus_role_id');
        $bonus_budget = $this->request->param('bonus_budget/f',0);
        $buy_bonus_budget = $this->request->param('buy_bonus_budget/f',0);
        $normal_bonus_budget = $this->request->param('normal_bonus_budget/f',0);
        $bonus_budget_type = $this->request->param('bonus_budget_type/d',0);
        $bonus_cycle_type = $this->request->param('bonus_cycle_type/d',0);
        $bonus_num = $this->request->param('bonus_num/d',0);
        //任务分红
        $status = $this->request->param('status/d',0);
        $consume_task_type = $this->request->param('consume_task_type/d',0);
        $consume_price = $this->request->param('consume_price/f',0);
        $consume_type = $this->request->param('consume_type/d',0);
        $consume_bonus_ratio = $this->request->param('consume_bonus_ratio/f',0);
        $toker_task_type = $this->request->param('toker_task_type/d',0);
        $toker_consume_price = $this->request->param('toker_consume_price/f',0);
        $toker_consume_type = $this->request->param('toker_consume_type/d',0);
        $toker_bonus_ratio = $this->request->param('toker_bonus_ratio/f',0);
        $promotion_task_type = $this->request->param('promotion_task_type/d',0);
        $promotion_share_num = $this->request->param('promotion_share_num/d',0);
        $promotion_bonus_ratio = $this->request->param('promotion_bonus_ratio/f',0);
        $is_memeber_once = $this->request->param('is_memeber_once/d',0);
        $same_member_time = $this->request->param('same_member_time/d',0);
        $join_role_id = $this->request->param('join_role_id');

        if(!in_array($bonus_cycle_type,[1,2,3]))   return $this->error('分红周期参数有误');

        Db::startTrans();

        try{
            //分红设置
            if(null === $bonus_setting = PartnerBonusSettingModel::where('shop_id',$this->request->shopId)->where(['is_delete'=>0])->find()){

                $bonus_setting = new PartnerBonusSettingModel();
                $bonus_setting->shop_id = $this->request->shopId;
                $bonus_setting->update_num = 0;
            }
            //只能设置不能修改（暂时不要）
            //if($bonus_setting->update_num>0) return $this->error('设置后不能修改，请联系平台');

            $bonus_setting->mon_av_turnover = $mon_av_turnover;
            $bonus_setting->total_bonus_share = $mon_av_turnover * 2;
            $bonus_setting->per_share_price = $per_share_price;
            $bonus_setting->total_share_num = $total_share_num;
            $bonus_setting->residue_share_num = $total_share_num;
            $bonus_setting->bonus_share_get_type = $bonus_share_get_type?implode(',',$bonus_share_get_type):$bonus_share_get_type;
            $bonus_setting->join_bonus_role_id = $join_bonus_role_id?implode(',',$join_bonus_role_id):$join_bonus_role_id;
            if($bonus_budget_type==1){
                $bonus_setting->bonus_budget = $bonus_budget;
            }else{
                $bonus_setting->buy_bonus_budget = $buy_bonus_budget;
                $bonus_setting->normal_bonus_budget = $normal_bonus_budget;
            }
            $bonus_setting->bonus_budget_type = $bonus_budget_type;
            $bonus_setting->bonus_cycle_type = $bonus_cycle_type;
            $bonus_setting->bonus_num = $bonus_num;
            $bonus_setting->update_num = 1;
            $bonus_setting->save();
            //任务分红设置
            if($status==1 && $toker_task_type==0 && $promotion_task_type==0 && $consume_task_type==0){
                return $this->error('至少设置一个有任务');
            }
            if($status==1 && !$join_role_id){
                return $this->error('至少选择一个参与任务分红合伙人类型');
            }
            if(null === $task_bonus_setting = PartnerTaskBonusSettingModel::where('shop_id',$this->request->shopId)->where(['is_delete'=>0])->find()){

                $task_bonus_setting = new PartnerTaskBonusSettingModel();
                $task_bonus_setting->shop_id = $this->request->shopId;
            }
            $task_bonus_setting->status = $status;
            $task_bonus_setting->consume_task_type = $consume_task_type;
            $task_bonus_setting->consume_price = $consume_price;
            $task_bonus_setting->consume_type = $consume_type;
            $task_bonus_setting->consume_bonus_ratio = $consume_bonus_ratio;
            $task_bonus_setting->toker_task_type = $toker_task_type;
            $task_bonus_setting->toker_consume_price = $toker_consume_price;
            $task_bonus_setting->toker_consume_type = $toker_consume_type;
            $task_bonus_setting->toker_bonus_ratio = $toker_bonus_ratio;
            $task_bonus_setting->promotion_task_type = $promotion_task_type;
            $task_bonus_setting->promotion_share_num = $promotion_share_num;
            $task_bonus_setting->promotion_bonus_ratio = $promotion_bonus_ratio;
            $task_bonus_setting->is_memeber_once = $is_memeber_once;
            $task_bonus_setting->same_member_time = $same_member_time;
            $task_bonus_setting->join_role_id = $join_role_id?implode(',',$join_role_id):$join_role_id;
            $task_bonus_setting->save();

            //如果当前门店没有生成分红数据，则生成分红的第一条数据（只需要第一次设置时生成，后面计划任务分红后在根据最新的分红设置生成下一条分红数据）（可分的期数=设置的最新期数-已分期数）（分红时除周期外 其他以最新设置为准）
            //$this->addBonusData($bonus_setting,$task_bonus_setting);

            Db::commit();

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('操作成功');



    }

    public function addBonusData($bonus_setting,$task_bonus_setting){

        if(null === $bonus =BonusModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->find()){

            $start_time = date('Y-m-d H:i:s');

            $bonus = new BonusModel();

            if($bonus_setting->bonus_cycle_type == 1){

                //第一期的月开始和结束时间
//                $start_time = date('Y-m-d H:i:s',strtotime(date('Y-m-d')));
//                $end_time = date('Y-m-d H:i:s',strtotime("+1 months", strtotime(date('Y-m-d'))));
                $end_time = date('Y-m-t', time()).' 23:59:59';
            }else{
                //第一期的季度开始和结束时间
//                $start_time = date('Y-m-d');
//                $end_time = date('Y-m-d H:i:s',strtotime("+3 months", strtotime(date('Y-m-d'))));
                $season = ceil((date('m'))/3);
                $end_time = date('Y-m-d H:i:s',mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y')));
            }

            $cousume_detail = [
                'consume_task_type'=>$task_bonus_setting->consume_task_type,
                'consume_price'=>$task_bonus_setting->consume_price,
                'consume_type'=>$task_bonus_setting->consume_type,
                'consume_bonus_ratio'=>$task_bonus_setting->consume_bonus_ratio,
            ];
            $toker_detail = [
                'toker_task_type'=>$task_bonus_setting->toker_task_type,
                'toker_consume_price'=>$task_bonus_setting->toker_consume_price,
                'toker_consume_type'=>$task_bonus_setting->toker_consume_type,
                'toker_bonus_ratio'=>$task_bonus_setting->toker_bonus_ratio,
            ];
            $promotion_detail = [
                'promotion_share_num'=>$task_bonus_setting->promotion_share_num,
                'promotion_bonus_ratio'=>$task_bonus_setting->promotion_bonus_ratio,
                'is_memeber_once'=>$task_bonus_setting->is_memeber_once,
                'same_member_time'=>$task_bonus_setting->same_member_time,
            ];
            $bonus->shop_id = $this->request->shopId;
            $bonus->start_time = $start_time;
            $bonus->end_time = $end_time;
            $bonus->task_status = $task_bonus_setting->status;
//            $bonus->cousume_detail = json_encode($cousume_detail,true);
//            $bonus->toker_detail = json_encode($toker_detail,true);
//            $bonus->promotion_detail = json_encode($promotion_detail,true);
            $bonus->save();
        }


    }

}

